import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useDispatch, useSelector } from '@umijs/max';
import { Button, message, Modal, Popconfirm, Switch, Tag } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useModel } from 'umi';
import AdminForm from './components/adminForm';

const Admin = () => {
  const { adminList } = useSelector((state) => state.admin);
  const dispatch = useDispatch();
  const formRef = useRef();

  const [isModalOpen, setIsModaOPen] = useState(false);
  const [adminInfo, setAdminInfo] = useState(null);
  const [messageApi, contextHolder] = message.useMessage();

  const model = useModel('@@initialState');

  useEffect(() => {
    if (!adminList.length) {
      dispatch({
        type: 'admin/_initAdminList',
      });
    }
  }, [adminList]);

  const columns = [
    {
      title: '登录账号',
      dataIndex: 'loginId',
      key: 'loginId',
      align: 'center',
    },
    {
      title: '登录密码',
      dataIndex: 'loginPwd',
      key: 'loginPwd',
      align: 'center',
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      align: 'center',
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      align: 'center',
      valueType: 'avatar',
    },
    {
      title: '权限',
      dataIndex: 'permission',
      key: 'permission',
      align: 'center',
      render: (_, row) => {
        let tag =
          row.permission === 1 ? (
            <Tag color="orange">超级管理员</Tag>
          ) : (
            <Tag color="blue">普通管理员</Tag>
          );
        return tag;
      },
    },
    {
      title: '账号状态',
      dataIndex: 'enabled',
      key: 'enabled',
      align: 'center',
      render: (_, row) => {
        if (model) {
          if (model.initialState.adminInfo._id === row._id) {
            return <Tag color="red">-</Tag>;
          }
        }
        return (
          <Switch
            checked={row.enabled}
            onChange={(value) => onChange(row, value)}
          />
        );
      },
    },

    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (_, row) => [
        <Button type="link" key="editTble" onClick={() => editHandle(row)}>
          编辑
        </Button>,
        <Popconfirm
          key="deleteTble"
          title="你确定要删除吗？"
          onConfirm={() => deleteHandle(row?._id)}
          okText="确定"
          cancelText="取消"
        >
          <Button type="link" key="deleteTable">
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  const deleteHandle = (adminId) => {
    dispatch({
      type: 'admin/_deleteAdmin',
      payload: adminId,
    });
  };

  const editHandle = (row) => {
    setAdminInfo(row);
    setIsModaOPen(true);
  };

  const onChange = (row, value) => {
    dispatch({
      type: 'admin/_updataAdmin',
      payload: {
        id: row._id,
        newAdminInfo: {
          enabled: value,
        },
      },
    });
    messageApi.open({
      type: 'success',
      content: value ? '该管理员已激活' : '该管理员已禁用',
    });
  };

  const setNewAdminInfo = (newVal) => {
    setAdminInfo(newVal);
  };
  const submitHandle = () => {
    dispatch({
      type: 'admin/_updataAdmin',
      payload: {
        id: adminInfo._id,
        newAdminInfo: adminInfo,
      },
    });
    messageApi.open({
      type: 'success',
      content: '修改管理员信息成功！',
    });
    setIsModaOPen(false);
  };
  const handleCancel = () => {
    setIsModaOPen(false);
  };

  return (
    <div>
      <PageContainer>
        <ProTable
          columns={columns}
          dataSource={adminList}
          rowKey={(row) => row?._id}
          search={false}
          formRef={formRef}
          pagination={{
            pageSize: 5,
          }}
        />
      </PageContainer>
      {isModalOpen ? (
        <Modal
          title="修改管理员信息"
          footer={false}
          open={isModalOpen}
          onCancel={handleCancel}
        >
          <AdminForm
            type="edit"
            adminInfo={adminInfo}
            setAdminInfo={setNewAdminInfo}
            submitHandle={submitHandle}
          />
        </Modal>
      ) : null}
      {contextHolder}
    </div>
  );
};

export default Admin;
